package com.yonyou.distribute.service;


import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Slf4j
@Service
public class RedissonService_2 {

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Value("${server.port}")
    private Integer port;

    @Transactional
    public void deduct() {

        RLock lock = this.redissonClient.getLock("lock");
        lock.lock();
        try{
            // 1、查询库存
            String stock = this.stringRedisTemplate.opsForValue().get("stock");
            // 2、判断库存是否充足
            if(!StringUtils.isEmpty(stock)){
                Integer st = Integer.valueOf(stock);
                if(st > 0){
                    //3、更新库存到数据库
                    this.stringRedisTemplate.opsForValue().set("stock", String.valueOf(--st));
                }
            }
            // redisson 自动续期
            TimeUnit.SECONDS.sleep(10);

            this.test();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 测试可重入锁
     */
    public void test() throws InterruptedException {
        RLock lock = this.redissonClient.getLock("lock");
        lock.lock();
        TimeUnit.SECONDS.sleep(5);
        lock.unlock();
    }
}
